package org.rayson.server;

import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class WorkerManager implements Manager, Runnable {

	private final Container container;
	private boolean running;
	private Thread thread;
	private long workerId;
	private final static int INITIALIZE_WORKER_COUNT = 4;
	private final Lock lock;

	private final static int SLEEP_INTERVAL = 1000;

	private final Condition condition;

	public WorkerManager(final Container container) {
		super();
		this.container = container;
		workerId = 0;
		lock = new ReentrantLock();
		condition = lock.newCondition();
	}

	@Override
	public Container getContainer() {
		return container;
	}

	@Override
	public String getName() {
		return "Worker Manager of " + getContainer();
	}

	private void quitOne() {

	}

	@Override
	public void run() {
		lock.lock();
		try {
			while (running) {
				condition.await(SLEEP_INTERVAL, TimeUnit.MILLISECONDS);
			}
		} catch (final InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	@Override
	public void start(final Properties properties) throws Exception {

		running = true;
		thread = new Thread(this, getName());
		thread.start();

		for (int i = 0; i < INITIALIZE_WORKER_COUNT; i++) {
			startNew();
		}

	}

	private void startNew() throws Exception {
		final Worker worker = new Worker(workerId++, container);
		worker.start(null);
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub

	}

}
